# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：    feishu_notifier.py
   Description:   企业级飞书通知工具类，支持发送文本和富文本卡片消息
-------------------------------------------------
"""

from __future__ import annotations

import requests
import json
import logging
from typing import List, Dict, Any
from pydantic import BaseModel, Field, ValidationError

# 初始化日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


class FeiShuConfig(BaseModel):
    webhook_url: str = Field(..., description="飞书群机器人Webhook URL")
    secret: str | None = Field(None, description="飞书机器人安全设置的密钥，可选")


class FeiShuNotifier:
    """
    企业级飞书通知工具类，支持发送文本和富文本卡片消息。
    """

    def __init__(self, config: FeiShuConfig):
        self.webhook_url = config.webhook_url
        self.secret = config.secret

    def send_text_message(self, content: str) -> Dict[str, Any]:
        """
        发送文本消息
        :param content: 消息内容
        :return: 飞书接口的响应结果
        """
        message = {
            "msg_type": "text",
            "content": {
                "text": content
            }
        }
        return self._send_message(message)

    def send_rich_text_message(self, title: str, elements: List[Dict[str, Any]]) -> Dict[str, Any]:
        """
        发送富文本卡片消息
        :param title: 消息标题
        :param elements: 富文本内容元素的列表
        :return: 飞书接口的响应结果
        """
        message = {
            "msg_type": "interactive",
            "card": {
                "config": {
                    "wide_screen_mode": True
                },
                "header": {
                    "title": {
                        "tag": "plain_text",
                        "content": title
                    }
                },
                "elements": elements
            }
        }
        return self._send_message(message)

    def _send_message(self, message: Dict[str, Any]) -> Dict[str, Any]:
        """
        发送消息到飞书群
        :param message: 消息内容字典
        :return: 飞书接口的响应结果
        """
        headers = {
            'Content-Type': 'application/json'
        }
        try:
            response = requests.post(self.webhook_url, headers=headers, data=json.dumps(message))
            response.raise_for_status()
            result = response.json()
            if result.get("StatusCode") != 0:
                logger.error(f"发送飞书消息失败: {result}")
            else:
                logger.info(f"飞书消息发送成功: {result}")
            return result
        except requests.exceptions.RequestException as e:
            logger.error(f"飞书消息发送失败，错误信息: {e}")
            return {"StatusCode": -1, "StatusMessage": str(e)}


# 示例使用
if __name__ == '__main__':
    # 初始化飞书配置
    try:
        config = FeiShuConfig(
            webhook_url="https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_WEBHOOK_TOKEN",
            secret=None  # 可选项，如果设置了加签安全，则填写对应的密钥
        )
    except ValidationError as e:
        logger.error(f"配置校验失败: {e}")
        raise

    notifier = FeiShuNotifier(config)
    # 发送文本消息
    notifier.send_text_message("测试用例执行成功！")
    # 发送富文本卡片消息
    rich_elements = [
        {
            "tag": "div",
            "text": {
                "tag": "plain_text",
                "content": "所有测试用例已成功通过，点击查看详细报告。"
            }
        },
        {
            "tag": "action",
            "actions": [
                {
                    "tag": "button",
                    "text": {
                        "tag": "plain_text",
                        "content": "查看报告"
                    },
                    "url": "https://example.com/report",
                    "type": "primary"
                }
            ]
        }
    ]
    notifier.send_rich_text_message("测试报告", rich_elements)
